package cn.edu.lcu.cs.javaprogramming.net;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ling
 * @date 2022/11/12 12:52
 */
public class HelloServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(7788);
        System.out.println("服务器等待连接中……");
        while (true) {
            // 等待客户端的连接，如果未连接，会一直等待……
            final Socket client = serverSocket.accept();
            // 启动新线程，与客户端传输数据
            new Thread() {
                public void run() {
                    // 与客户端建立了连接，显示连接的地址与端口
                    String hostAddress = client.getInetAddress().getHostAddress();
                    int port = client.getPort();
                    System.out.printf("与 %s : %d 建立了连接\n", hostAddress, port);
                    // 获取客户端的输出流，用于写数据到客户端
                    try (OutputStream outputStream = client.getOutputStream()) {
                        // 写数据到客户端
                        outputStream.write("Helloworld".getBytes());
                        // 为了更好的演示效果，故意休眠若干时间
                        Thread.sleep(10000);

                        System.out.printf("与 %s : %d 的数据传输结束\n", hostAddress, port);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }
}
